import React, { useEffect, useState, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import ProfileSettings from './Components/ProfileSettings';
import PlanInfo from './Components/PlanInfo';
import LanguageSettings from './Components/LanguageSettings';
import NotificationSettings from './Components/NotificationSettings';
import DangerZone from './Components/DangerZone';
import MyBill from './Components/MyBill';//我的账单按钮
import { request } from '@/api/request';
import CryptoJS from 'crypto-js';

// 定义用户信息解密的函数 
const decryptData = (encrypted: any) => {
    try {
        const key = CryptoJS.enc.Utf8.parse('yydskno1me888888');
        const decrypted = CryptoJS.AES.decrypt(encrypted, key, {
            mode: CryptoJS.mode.ECB,
            padding: CryptoJS.pad.Pkcs7,
        });
        const decryptedStr = CryptoJS.enc.Utf8.stringify(decrypted);
        // 将解密后的字符串转换为JSON对象
        return JSON.parse(decryptedStr);
    } catch (error) {
        // console.error('解密或解析JSON失败:', error);
        console.error('decrypt or parse JSON failed', error);
        return null;
    }
};


const Settings: React.FC = () => {
    const { t, i18n } = useTranslation();
    const [userData, setUserData] = useState<any>(null);
    const contentRef = useRef<HTMLDivElement>(null);
    const lightRef = useRef<HTMLDivElement>(null);

    // 鼠标打灯效果事件
    // const handleMouseMove = (e: React.MouseEvent<HTMLDivElement, MouseEvent>) => {
    //     const rect = contentRef.current?.getBoundingClientRect();
    //     if (rect && lightRef.current) {
    //         // 确保打灯效果可见
    //         lightRef.current.style.display = 'block';
    //         const x = e.clientX - rect.left;
    //         const y = e.clientY - rect.top;
    //         lightRef.current.style.setProperty('--x', `${x}px`);
    //         lightRef.current.style.setProperty('--y', `${y}px`);
    //     }
    // };
    const handleMouseLeave = () => {
        if (lightRef.current) {
            // 鼠标离开时隐藏打灯效果
            lightRef.current.style.display = 'none';
        }
    };
    // 获取用户信息
    const getuserInformation = async () => {
        const res = await request.get('/api/visitor/getUserInformation', {
            params: {
                fields: 'avatar, displayName,gender, email, phone,membershipTier, tokensBalance',
            }
        })
        if (res.data.success === true) {
            const decryptedData = decryptData(res.data.data.encryptedData);
            console.log('获取到的用户数据', decryptedData);
            if (decryptedData) {
                // 只存储需要的字段，避免冗余
                setUserData({
                    avatar: decryptedData.avatar,
                    displayName: decryptedData.displayName,
                    gender: decryptedData.gender,
                    email: decryptedData.email,
                    phone: decryptedData.phone,
                    membershipTier: decryptedData.membershipTier,
                    tokensBalance: decryptedData.tokensBalance,
                });
            }
        }
    }

    // 会员类型映射函数
    const getPlanTypeName = (membershipTier: any, language: string) => {
        if (membershipTier === null || membershipTier === undefined) {
            if (language === 'zh') return '普通会员';
            if (language === 'en') return 'free';
            if (language === 'ja') return '一般ユーザー';
            return 'free';
        }
        if (membershipTier === 1) {
            if (language === 'zh') return '白银会员';
            if (language === 'en') return 'Prelude';
            if (language === 'ja') return '初心者の旅';
            return 'Prelude';
        }
        if (membershipTier === 2) {
            if (language === 'zh') return '黄金会员';
            if (language === 'en') return 'Affinity';
            if (language === 'ja') return '絆の旅路';
            return 'Affinity';
        }
        if (membershipTier === 3) {
            if (language === 'zh') return '钻石会员';
            if (language === 'en') return 'Soulmate';
            if (language === 'ja') return '魂の伴侶';
            return 'Soulmate';
        }
        return '';
    };

    // 从后端获取用户的信息 
    useEffect(() => {
        getuserInformation()
    }, [])

    // 编辑后刷新
    const handleProfileUpdated = () => {
        getuserInformation();
    };


    // 组装传递给ProfileSettings的props
    const profileProps = {
        avatar: userData?.avatar,
        displayName: userData?.displayName,
        gender: userData?.gender, // 这里去掉 ?? 'male'
        email: userData?.email,
        phone: userData?.phone,
        tokensBalance: userData?.tokensBalance,
        membershipTier: userData?.membershipTier,
        onProfileUpdated: handleProfileUpdated, // 传递回调
    };

    // 组装传递给PlanInfo的planType
    const planType = getPlanTypeName(userData?.membershipTier, i18n.language);

    return (
        <div
            className='w-full relative'
            ref={contentRef}
            // onMouseMove={handleMouseMove}
            onMouseLeave={handleMouseLeave}
        >
            {/* 打灯遮罩层 */}
            {/* <div
                ref={lightRef}
                className="mouse-light-settings"
                style={{ pointerEvents: 'none' }}
            /> */}

            < div className="text-white text-[2rem] text-center mb-8 mt-8" >
                {t('settings.profileSettings')}
            </div >

            {/* 内容  */}
            <div
                className='w-[90%] md:w-[55%] m-auto relative overflow-hidden'
            >
                {/* 个人资料设置 */}
                < ProfileSettings {...profileProps} />

                {/* 当前计划信息 */}
                < PlanInfo planType={planType} membershipTier={userData?.membershipTier} />

                {/* 消费账单页面入口按钮  */}
                <MyBill />

                {/* 语言设置 */}
                <LanguageSettings />

                {/* 通知设置 */}
                {/* <NotificationSettings /> */}

                {/* 危险区域 - 删除账号 */}
                {/* <DangerZone /> */}
            </div>

        </div >
    );
};

export default Settings;
